//
//  PlayViewController.m
//  SBVideoCaptureDemo
//
//  Created by Pandara on 14-8-18.
//  Copyright (c) 2014年 Pandara. All rights reserved.
//

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com

#import "PlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SBCaptureDefine.h"
//#import "MeViewController.h"

#import "XLPersonPageViewController.h"
#import "XLVideoSetController.h"
#import "ZBMessageTextView.h"
#import "Sender.h"
#import "HelpTool.h"

#import "NSString+Ext.h"

#import "MBProgressHUD.h"
#import "ZYQAssetPickerController.h"
#import "SBCaptureToolKit.h"
#import "SFHFKeychainUtils.h"


#import "TXYUploadManager.h"
#import "UILabel+dynamicSize.h"
#define  SIGN_URL @"http://test.m.interface.baomihua.com/weise/WSVideoAction.ashx?action=sign&bucketName=bucket"

#define  ONE_SIGN_URL @"http://203.195.194.28/php/getsignv2.php?bucket=filename&service=cos&expired=0&path="

#import <MobileCoreServices/UTCoreTypes.h>
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <MediaPlayer/MediaPlayer.h>
 
#import "XLHTTPSessionManager.h"
#import "XLAccountManager.h"
#import <ReactiveCocoa.h>


#define DECLARE_WEAK_SELF __typeof(&*self) __weak weakSelf = self
#define DECLARE_STRONG_SELF __typeof(&*self) __strong strongSelf = weakSelf


@interface PlayViewController () <UITextViewDelegate,senderDelegate, ZYQAssetPickerControllerDelegate, UINavigationControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
    Sender *dataSender;
    MBProgressHUD *_HUD;
    NSString *appId;
    NSString *persistenceId;
    NSString *bucket;
    TXYVideoUploadTaskRsp *videoResp;
    NSString *videoPath;
    TXYVideoUploadTask *uploadVideoTask;
    TXYPhotoUploadTaskRsp *photoResp;
    NSString *imagepersistenceId;
    NSString *imagebucket;
    
    NSString *  videoUrlName;
}

@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) NSURL *videoFileURL;
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) UIButton *playButton;
@property (strong, nonatomic) AVPlayerItem *playerItem;

@property (assign, nonatomic) NSInteger totalDur;
@property (assign, nonatomic) NSString *allComment;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, weak, readwrite) ZBMessageTextView *messageInputTextView;
@property (nonatomic, copy) NSString *fileName;
@property (nonatomic, strong) UIImage *videoImage;
@property (nonatomic, strong) UIView *videoView;
@property (nonatomic, assign) float videoWidth;
@property (nonatomic, assign) float videoHeigh;
@property (nonatomic, strong) NSString * videoScreen;

@property (nonatomic,strong) NSString * upVideourl;
//腾讯云
@property (nonatomic,strong) TXYUploadManager *uploadVideoManager;
@property (nonatomic,strong) TXYVideoUploadTask *uploadVideoTask;
@property (nonatomic,copy) NSString *sign;
@property (nonatomic,copy) NSString *imageSign;
@property NSString *ok;
@property (nonatomic,strong) TXYUploadManager *uploadImageManager;
@property (nonatomic,strong) TXYPhotoUploadTask *uploadPhotoTask;
@property (nonatomic,copy) NSString *sendImageStr;


@end

@implementation PlayViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withVideoFileURL:(NSURL *)videoFileURL withTotalDur:(NSInteger)totalDur withAllComment:(NSInteger)allComment  withWidth:(float)width withHeight:(float)height name:(NSString *)name  withVidoInputUrlStr:(NSString *)urlPath withScreen:(NSString *)videScreen withactiveId:(NSString *)acID;
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.videoFileURL = videoFileURL;
        self.totalDur = totalDur;
        self.allComment =  [NSString stringWithFormat:@"大小 ：%@", [self getCommentSize:allComment]];
        NSString *token = [[HelpTool getIOSuuid] substringToIndex:7];

        self.fileName = [NSString stringWithFormat:@"%@_%@", token, name];
        self.view.frame = CGRectMake(0, 0, kMainScreenBounds.size.width, kMainScreenBounds.size.height + 200);
        self.videoWidth = width;
        self.videoHeigh = height;
        videoPath = urlPath;
        self.videoScreen = videScreen;
        self.gcActivityID = acID;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    self.fd_interactivePopDisabled = YES;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = RGB(236, 236, 234);
    self.navigationController.navigationBarHidden = YES;
    UIView *top = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kMainScreenBounds.size.width, 64)];
    top.backgroundColor = [UIColor whiteColor];
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backButton.frame = CGRectMake(0, 20, 80, 44);
    [self.backButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(pressBackButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.backButton setTitleColor:RGB(119, 119, 119) forState:UIControlStateNormal];
    
    UILabel *navTitle = [[UILabel alloc] initWithFrame:CGRectMake(90, 20, kMainScreenBounds.size.width - 180, 44)];
    navTitle.text = @"传视频";
    navTitle.textColor = RGB(229, 32, 121);
    navTitle.font = [UIFont systemFontOfSize:18];
    navTitle.textAlignment = NSTextAlignmentCenter;
    [top addSubview:navTitle];
    
    UIButton *shanchuanBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    shanchuanBtn.frame = CGRectMake(kMainScreenBounds.size.width - 80, 20, 80, 44);
    [shanchuanBtn setTitle:@"上传" forState:UIControlStateNormal];
    [shanchuanBtn addTarget:self action:@selector(ShangChuanButton:) forControlEvents:UIControlEventTouchUpInside];
    [shanchuanBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [top addSubview:shanchuanBtn];
    
    [top addSubview:self.backButton];
    
    [self.view addSubview:top];
    
    UIView *headImage = [[UIView alloc] initWithFrame:CGRectMake(0, 74, kMainScreenBounds.size.width, 150)];
    headImage.userInteractionEnabled = YES;
    headImage.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headImage];
    // 初始化输入框
    ZBMessageTextView *textView = [[ZBMessageTextView alloc] initWithFrame:CGRectMake(0, 0, kMainScreenBounds.size.width, 150)];
    textView.returnKeyType = UIReturnKeyDefault;
    //    textView.enablesReturnKeyAutomatically = YES; // UITextView内部判断send按钮是否可以用
    textView.placeHolder = @"说点什么吧...";
    
    textView.delegate = self;
    [headImage addSubview:textView];
    self.messageInputTextView = textView;
    
    [self initPlayLayer];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [top addGestureRecognizer:tap];
    appId = @"10063237";//10063237
    bucket = @"dynamic"; //上传视频入口：发表动态：bucket=bucket 发红包视频：bucket=tempvideo
    
    persistenceId = @"videoID";//自定义,唯一,没有限制
    //上传视频总共五步之     第二步 向自己的业务服务器请求 上传image所需要的签名
    [self getUploadVidoSign];
    
    //上传视频总共五步之     第三步: 初始化上传工具
    _uploadVideoManager = [[TXYUploadManager alloc] initWithCloudType:TXYCloudTypeForVideo
                                                        persistenceId:persistenceId
                                                                appId:appId];
    
    imagebucket = @"bucketimg";//test2p//
    imagepersistenceId = @"persistenceId";//自定义,唯一,没有限制persistenceId
    //上传图片总共五步之     第二步 向自己的业务服务器请求 上传image所需要的签名
    [self getUploadImageSign];
    //上传图片总共五步之     第三步: 初始化上传工具
    _uploadImageManager = [[TXYUploadManager alloc] initWithCloudType:TXYCloudTypeForImage
                                                        persistenceId:imagepersistenceId
                                                                appId:appId];
    
    
}
#pragma mark －network

-(void)getUploadVidoSign
{
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    //时间戳
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID, uid, publicKey, sTime];
    nat = [nat md5Encrypt];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    
    
    NSDictionary *cloundSignDic =[NSDictionary dictionaryWithObjectsAndKeys:@"2",@"type",@"dynamic",@"BucketName",uid,@"UserID",locationString,@"Timestamp",nat,@"AppSign", nil];
    
    [BMHHTTPSession GET:@"/MobileInterface/Video/VideoCloud.ashx" paraments:cloundSignDic success:^(id  _Nullable JSON) {
        NSLog(@"云存储签名==========-=-=-----%@", JSON);
        
        self.sign = JSON[@"result"][@"errmsg"];
        
        
    } failure:^(NSError * _Nullable error) {
        
    }];

    
}
-(void)getUploadImageSign
{
    
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    //时间戳
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID, uid, publicKey, sTime];
    nat = [nat md5Encrypt];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    
    
    NSDictionary *cloundSignDic =[NSDictionary dictionaryWithObjectsAndKeys:@"2",@"type",@"bucketimg",@"BucketName",uid,@"UserID",locationString,@"Timestamp",nat,@"AppSign", nil];
    
    [BMHHTTPSession GET:@"/MobileInterface/Video/VideoCloud.ashx" paraments:cloundSignDic success:^(id  _Nullable JSON) {
        NSLog(@"云存储签名==========-=-=-----%@", JSON);
        
        self.imageSign = JSON[@"result"][@"errmsg"];
        
        
    } failure:^(NSError * _Nullable error) {
        
    }];

    
    

    
}

- (void)ShangChuanButton:(UIButton *)sender {
    [self.messageInputTextView resignFirstResponder];
    
    if (self.messageInputTextView.text.length <= 0) {
        
        [HelpTool startTipViewWithText:@"请填写视频名称" duration:1.0 type:kTipViewTypeNone];
        [self hiddenLoadingWihtView:self.view];
        return;
    }
    
    [self showLoadingWithView:self.view];
    
//    _HUD = [[MBProgressHUD alloc] initWithView:self.view];
//    _HUD.label.text = LoadingUpload;
//    [_HUD showAnimated:YES];

    if(!self.imageSign)[self getUploadImageSign];
    //上传图片总共五步之   第四步: 初始化上传化上传任务
    _uploadPhotoTask = [[TXYPhotoUploadTask alloc] initWithImageData: UIImageJPEGRepresentation(self.videoImage, 1.0)
                                                            fileName:@"name"
                                                                sign:self.imageSign
                                                              bucket:imagebucket
                                                         expiredDate:0
                                                          msgContext:@"服务器透穿信息"
                                                              fileId:nil];
    //上传图片总共四步之    第五步: 上传
    [_uploadImageManager upload:_uploadPhotoTask
                       complete:^(TXYTaskRsp *resp, NSDictionary *context) {
                           
                           photoResp = (TXYPhotoUploadTaskRsp *)resp;
                           NSLog(@"上传图片的url%@ 上传图片的fileid = %@",photoResp.photoURL,photoResp.photoFileId);
                           self.sendImageStr = photoResp.photoURL;
                           NSLog(@"upload return=%d",photoResp.retCode);
                           
                               [self uploadVideoWihtVideoPath:[NSString stringWithFormat:@"%@", self.videoFileURL]];
                               
                        
                           
                           
                       }
                       progress:^(int64_t totalSize, int64_t sendSize, NSDictionary *context) {
                           //命中妙传，不走这里的！
                           NSLog(@" totalSize %lld",totalSize);
                           NSLog(@" sendSize %lld",sendSize);
                           NSLog(@" sendSize %@",context);
                           
                       }
                    stateChange:^(TXYUploadTaskState state, NSDictionary *context) {
                        switch (state) {
                            case TXYUploadTaskStateWait:
                                NSLog(@"任务等待中");
                                break;
                            case TXYUploadTaskStateConnecting:
                                NSLog(@"任务连接中");
                                break;
                            case TXYUploadTaskStateFail:
                                [self hiddenLoadingWihtView:self.view];
                                //[_HUD hideAnimated:YES];
                                NSLog(@"任务失败");
                                break;
                            case TXYUploadTaskStateSuccess:
                                NSLog(@"任务成功");
                                break;
                            default:
                                break;
                        }}];
    
    
    
    
}
#pragma mark - SDK Method
// 上传方法
-(void)uploadVideoWihtVideoPath:(NSString *)path
{
    
    if (videoResp.fileURL.length > 0) {
        [self sendrDateFirst];
        return;
    }
    
    
    static int PAGE = 10;
    PAGE++;
    NSString * videTitleStr = [NSString stringWithFormat:@"%@%d",NSUser_object(UserID),PAGE];
    NSLog(@"=====path== %@",path);
    NSLog(@"=====videoPath==%@",videoPath);
    if(!self.sign){
        [self getUploadVidoSign];
    }
    TXYVideoFileInfo *videoFileInfo = [[TXYVideoFileInfo alloc]init];
    videoFileInfo.title = videTitleStr;
    videoFileInfo.desc = @"videodesc1";
    videoFileInfo.isCheck = 0;
    videoFileInfo.coverUrl= self.sendImageStr;//视频的自定义封面
    //上传视频总共四步之    第四步: 初始化上传化上传任务
    NSString *dir =[NSString stringWithFormat:@"/"];//[NSString stringWithFormat:@"/12",bucket];
    uploadVideoTask = [[TXYVideoUploadTask alloc] initWithPath:videoPath
                                                          sign:_sign
                                                        bucket:bucket
                                                      fileName:self.fileName
                                               customAttribute:@"customAttribute"
                                               uploadDirectory:dir
                                                 videoFileInfo:videoFileInfo
                                                    msgContext:@"msgContext"
                                                    insertOnly:NO];
    //上传视频总共五步之   第五步: 上传任务
    DECLARE_WEAK_SELF;
    BOOL isSuccess = [_uploadVideoManager upload:uploadVideoTask
                       complete:^(TXYTaskRsp *resp, NSDictionary *context) {
                           DECLARE_STRONG_SELF;
                           if (!strongSelf) return;
                           videoResp = (TXYVideoUploadTaskRsp *)resp;
                           NSLog(@"上传视频的url%@ 上传视频的fileid = %@",videoResp.fileURL,videoResp.fileId);
                           NSLog(@"video is source url%@",videoResp.sourceURL);
                           if ([videoResp.fileURL isEqualToString:@""] || videoResp.fileURL == nil) {
                               [self hiddenLoadingWihtView:self.view];
                               //[_HUD hideAnimated:YES];

                               [HelpTool startTipViewWithText:@"上传失败" duration:1 type:kTipViewTypeNone];
                           }else {
                               
                               videoUrlName = videoResp.fileURL;
                               
                               [self sendrDateFirst];
 
                           }
                           
                       }
                       progress:^(int64_t totalSize, int64_t sendSize, NSDictionary *context) {
                           //命中妙传，不走这里的！
                           NSLog(@" totalSize %lld",totalSize);
                           NSLog(@" sendSize %lld",sendSize);
                           NSLog(@" sendSize %@",context);
                       }
                    stateChange:^(TXYUploadTaskState state, NSDictionary *context) {
                        switch (state) {
                            case TXYUploadTaskStateWait:
                                NSLog(@"demoapp log 任务等待中");
                                break;
                            case TXYUploadTaskStateConnecting:
                                NSLog(@"demoapp log 任务连接中");
                                break;
                            case TXYUploadTaskStateFail:
                                [HelpTool startTipViewWithText:@"上传失败" duration:1 type:kTipViewTypeNone];

                                [self hiddenLoadingWihtView:self.view];
                                //[_HUD hideAnimated:YES];
                                NSLog(@"demoapp log 任务失败");
                                break;
                            case TXYUploadTaskStateSuccess:
                                NSLog(@"demoapp log 任务成功");
                                break;
                            default:
                                break;
                        }}];
    if (isSuccess == NO) {
        [self hiddenLoadingWihtView:self.view];
        [HelpTool startTipViewWithText:@"添加上传任务失败" duration:1 type:kTipViewTypeNone];
    }
}

#pragma mark - 上传视频接口
- (void)sendrDateFirst {
    
    _ComeFromEditVC = NO;
    
    NSString *bmhuid  = [NSString stringWithFormat:@"%@",NSUser_object(UserID)];
    
    UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController *nav = [tabVC.viewControllers objectAtIndex:tabVC.viewControllers.count - 1];
    UIViewController *personVC;
    for (UIViewController *vc in nav.viewControllers) {
        if ([vc isKindOfClass:[XLVideoSetController class]]) {
            _ComeFromEditVC = YES;
            break;
        }
    }
    
    if (_ComeFromEditVC) {
        
        
        if (self.messageInputTextView.text.length <= 0) {
            
            [HelpTool startTipViewWithText:@"请填写视频名称" duration:1.0 type:kTipViewTypeNone];
            [self hiddenLoadingWihtView:self.view];
            return;
        }
        
        if (self.fileName.length <= 0) {
            NSLog(@"没有视频信息");
            [self hiddenLoadingWihtView:self.view];
            return;
        }
        
        if (self.sendImageStr.length <=0) {
            NSLog(@"没有视频连接地址");
            [self hiddenLoadingWihtView:self.view];
            return;
        }
        
        if (self.totalDur <= 0) {
            NSLog(@"请传递视频时长");
            [self hiddenLoadingWihtView:self.view];
            return;
        }
        
        
        
        
        
        [[[XLHTTPSessionManager sharedManager] XLV2POST:@"/api/v2/DynamicVideo/PublishDynamicVideo" parameters:@{
                                                                                                                 @"UserID":bmhuid,
                                                                                                                 @"Title":self.messageInputTextView.text,
                                                                                                                 @"Content":self.fileName,
                                                                                                                 @"PicUrl":self.sendImageStr,
                                                                                                                 @"ScreenType":self.videoScreen,
                                                                                                                 @"Width":[NSString stringWithFormat:@"%.0f",self.videoWidth],
                                                                                                                 @"Height":[NSString stringWithFormat:@"%.0f",self.videoHeigh],
                                                                                                                 @"PlayCost":[NSString stringWithFormat:@"%ld",(long)self.totalDur],
                                                                                                                 @"Status":@1
                                                                                                                 
                                                                                                                 } resultClass:nil] subscribeNext:^(id x) {
            
            if (x) {
                [self hiddenLoadingWihtView:self.view];
                [HelpTool startTipViewWithText:@"上传成功" duration:1.0 type:kTipViewTypeNone];
                
                videoUrlName = nil;
                
//                NSString *filePath = [self getDirectoryOfDocumentFileWithName:self.fileName];
//                NSString *vidUrl = [self getFilePath];
//                if (filePath) {
//                    [self removeFileAtPath:filePath];
//                    [self removeFileAtPath:vidUrl];
//                    [self removeFileAtPath:[self getQuPaiVideoPath]];
//                }
                UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                UINavigationController *nav = [tabVC.viewControllers objectAtIndex:tabVC.viewControllers.count - 1];
                UIViewController *personVC;
                for (UIViewController *vc in nav.viewControllers) {
                    if ([vc isKindOfClass:[XLVideoSetController class]]) {
                        personVC = vc;
                        break;
                    }
                }
                if (personVC) {
                    [nav popToViewController:personVC animated:NO];
                } else {
                    [nav popToRootViewControllerAnimated:NO];
                }
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            }else{
                [self hiddenLoadingWihtView:self.view];
                //上传失败
                [HelpTool startTipViewWithText:@"上传失败" duration:1.0 type:kTipViewTypeNone];
            }
            
            
            
        
            
        } error:^(NSError *error) {
            BMHLog(@"%@",error);
            [self hiddenLoadingWihtView:self.view];
        }];
        
    }else{
        
        [[[XLHTTPSessionManager sharedManager] getPublishDynamicVideoWihtUserID:bmhuid titlles:self.messageInputTextView.text content:self.fileName picUrl:self.sendImageStr screenType:self.videoScreen width:[NSString stringWithFormat:@"%.0f",self.videoWidth] height:[NSString stringWithFormat:@"%.0f",self.videoHeigh] playCost:[NSString stringWithFormat:@"%ld",(long)self.totalDur] andSign:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(id x) {
            [self hiddenLoadingWihtView:self.view];
            NSString * dataState = [NSString stringWithFormat:@"%@",x[@"success"]];
            if ([dataState isEqualToString:@"0"]) {
                    //上传成功
                    [HelpTool startTipViewWithText:@"上传成功" duration:1.0 type:kTipViewTypeNone];
                    NSString *filePath = [self getDirectoryOfDocumentFileWithName:self.fileName];
                    NSString *vidUrl = [self getFilePath];
                    if (filePath) {
                        [self removeFileAtPath:filePath];
                        [self removeFileAtPath:vidUrl];
                        [self removeFileAtPath:[self getQuPaiVideoPath]];
                    }
                
                
                
                    UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                    UINavigationController *nav = [tabVC.viewControllers objectAtIndex:3];
                
                UIViewController *VideoSetVC;
                for (UIViewController *vc in nav.viewControllers) {
                    if ([vc isKindOfClass:[XLVideoSetController class]]) {
                        VideoSetVC = vc;
                        break;
                    }
                }
                if (VideoSetVC) {
                    [nav popToViewController:VideoSetVC animated:NO];
                } else {
                    [nav popToRootViewControllerAnimated:NO];
                    
                }
                
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ReleaseSuccessNotice" object:nil];
            }else{
                [self hiddenLoadingWihtView:self.view];
                //上传失败
                [HelpTool startTipViewWithText:@"上传失败" duration:1.0 type:kTipViewTypeNone];
            }
            
            
        } error:^(NSError *error) {
            BMHLog(@"%@",error);
            [self hiddenLoadingWihtView:self.view];
        }];
        
    }

    
}

#pragma mark -

- (void)textViewDidChange:(UITextView *)textView{
    
    
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(avPlayerItemDidPlayToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    NSString *filePath = [self getDirectoryOfDocumentFileWithName:self.fileName];
    if (filePath) {
        [self removeFileAtPath:filePath];
    }
}

- (void)initPlayLayer
{
    [self.videoView removeFromSuperview];
    UIView *videoImage = [[UIView alloc] initWithFrame:CGRectMake(0, 74 + 150 + 10, kMainScreenBounds.size.width, 120)];
    videoImage.userInteractionEnabled = YES;
    videoImage.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:videoImage];
    self.videoView = videoImage;
    
    if (!_videoFileURL) {
        UIButton *btnphoto=[UIButton buttonWithType:UIButtonTypeCustom];
        [btnphoto setFrame:CGRectMake(20, 10, 100, 100)];//
        [btnphoto setImage:[UIImage imageNamed:@"jiahao@2x.png"] forState:UIControlStateNormal];
        [btnphoto setImage:[UIImage imageNamed:@"jiahao@2x.png"] forState:UIControlStateSelected];
        [btnphoto addTarget:self action:@selector(handleJiaBtn) forControlEvents:UIControlEventTouchUpInside];
        [videoImage addSubview:btnphoto];
        
        
    }else {
        AVURLAsset *movieAsset = [AVURLAsset URLAssetWithURL:_videoFileURL options:nil];
        //视频截图
        AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:movieAsset];
        
        
        
        generator.appliesPreferredTrackTransform = YES;
        
        //        generator.maximumSize = CGSizeMake(1136, 640);
        
        
        
        NSError *error = nil;
        
        CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(10, 10) actualTime:NULL error:&error];
        
        UIImage *image = [UIImage imageWithCGImage: img];
        //    _playerLayer.frame = CGRectMake(20, 10, 100, 100);
        
        
        self.videoImage = image;
        
        UIImageView *videoImae  = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, 100, 100)];
        videoImae.image = image;
        videoImae.userInteractionEnabled = YES;
        videoImae.clipsToBounds = YES;
        videoImae.contentMode = UIViewContentModeScaleAspectFill;
        videoImae.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [videoImae setContentScaleFactor:[[UIScreen mainScreen] scale]];
        [videoImage addSubview:videoImae];
        
        UILabel *timeLab = [[UILabel alloc] initWithFrame:CGRectMake(130, 30, 200, 30)];
        timeLab.textColor = RGB(119, 119, 119);
        timeLab.text = [NSString stringWithFormat:@"时间 ：%lds", self.totalDur];
        [videoImage addSubview:timeLab];
        
        UILabel *commentLab = [[UILabel alloc] initWithFrame:CGRectMake(130, 60, 200, 30)];
        commentLab.textColor = RGB(119, 119, 119);
        commentLab.text = self.allComment;
        [videoImage addSubview:commentLab];
        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        tap.numberOfTapsRequired = 1;
        [videoImage addGestureRecognizer:tap];
        
        
        self.playButton = [[UIButton alloc] initWithFrame:videoImae.frame];
        [_playButton addTarget:self action:@selector(pressPlayButton:) forControlEvents:UIControlEventTouchUpInside];
        [videoImage addSubview:_playButton];
        
        
    }
    
    
}
- (NSString *)getCommentSize:(NSInteger)comment {
    NSString *allComment;
    
    if (comment > 1024) {
        CGFloat floCom  = 0;
        floCom = comment / 1024.0;
        allComment = [NSString stringWithFormat:@"%0.1fM", floCom];
        allComment = [allComment stringByReplacingOccurrencesOfString:@".0" withString:@""];
    }else {
        allComment = [NSString stringWithFormat:@"%ldKB", comment];
    }
    
    return allComment;
}
- (void)handleTap:(UITapGestureRecognizer *)sender {
    [self.messageInputTextView resignFirstResponder];
    
}
- (void)pressPlayButton:(UIButton *)button
{
    [self.messageInputTextView resignFirstResponder];
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.topView = topView;
    
    topView.backgroundColor = [UIColor whiteColor];
    UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [removeBtn setTitle:@"退出画面" forState:UIControlStateNormal];
    [removeBtn setTitleColor:RGB(229, 32, 121) forState:UIControlStateNormal];
    removeBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    removeBtn.frame = CGRectMake(0, 64, kMainScreenBounds.size.width / 2 , 30);
    [removeBtn addTarget:self action:@selector(handleremoveTop) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:removeBtn];
    
//    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [deleteBtn setTitle:@"删除视频" forState:UIControlStateNormal];
//    [deleteBtn setTitleColor:RGB(229, 32, 121) forState:UIControlStateNormal];
//    deleteBtn.titleLabel.font = [UIFont systemFontOfSize:17];
//    deleteBtn.frame = CGRectMake(kMainScreenBounds.size.width / 2, 64, kMainScreenBounds.size.width / 2, 30);
//    [deleteBtn addTarget:self action:@selector(handledeleteBtn) forControlEvents:UIControlEventTouchUpInside];
//    [topView addSubview:deleteBtn];
    
    
    
    AVURLAsset *movieAsset = [AVURLAsset URLAssetWithURL:self.videoFileURL options:nil];
    
    self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 64 + 30, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height- 150);
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [topView.layer addSublayer:_playerLayer];
    self.topView.hidden = NO;
    [self.view addSubview:self.topView];
    
    [_playerItem seekToTime:kCMTimeZero];
    [_player play];
    //    _playButton.alpha = 0.0f;
}
- (void)handledeleteBtn {
    self.topView.hidden = YES;
    [_player pause];
    self.videoFileURL = nil;
    [self initPlayLayer];
    
}
- (void)handleremoveTop{
    
    self.topView.hidden = YES;
    [_player pause];
}


- (void)handleJiaBtn {
    
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc]init];
    picker.maximumNumberOfSelection = 1;
    picker.assetsFilter = [ALAssetsFilter allVideos];
    picker.showEmptyGroups = NO;
    picker.wetherPhoto = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,NSDictionary *bindings){
        if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType]isEqual:ALAssetTypePhoto]) {
            NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration]doubleValue];
            return duration >= 5;
        }else{
            return  YES;
        }
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    NSData        *date        = [assets[0] valueForProperty:ALAssetPropertyDate];
    //UIImage       *image       = [UIImage imageWithCGImage:[assets[0] thumbnail]];
    NSString      *fileName    = [[assets[0] defaultRepresentation] filename];
    NSURL         *url         = [[assets[0] defaultRepresentation] url];
    NSInteger      fileSize    = [[assets[0] defaultRepresentation] size] / 1024;
    NSMutableData *mmdat = [NSMutableData dataWithContentsOfURL:url];
    [mmdat writeToFile:[self getFilePath] atomically:YES];
    
    ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
    [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) // substitute YOURURL with your url of video
     {
         ALAssetRepresentation *rep = [asset defaultRepresentation];
         Byte *buffer = (Byte*)malloc(rep.size);
         NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
         NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
         [data writeToFile:[self getFilePath] atomically:YES]; //you can remove this if only nsdata needed
     }
                 failureBlock:^(NSError *err) {
                     NSLog(@"Error: %@",[err localizedDescription]);
                 }];
    
    videoPath = [self getFilePath];
    NSString *token = [[HelpTool getIOSuuid] substringToIndex:5];
    
    self.fileName = [NSString stringWithFormat:@"%@_%@", token, fileName];

    NSLog(@"=====urlpath==%@",videoPath);
    
    NSLog(@"date = %@",date);
    NSLog(@"fileName = %@",fileName);
    NSLog(@"url = %@",url);
    NSLog(@"fileSize = %ld",fileSize);
    
    
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                     forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];  // 初始化视频媒体文件
    float  second = 0;
    
    //second = urlAsset.duration.value * 1.0 / urlAsset.duration.timescale; // 获取视频总时长,单位秒
    
    NSString *allComment;
    
    allComment = [NSString stringWithFormat:@"%0.1f",(long ) urlAsset.duration.value * 1.0 / urlAsset.duration.timescale];
    allComment = [allComment stringByReplacingOccurrencesOfString:@".0" withString:@""];
    self.totalDur = [allComment integerValue];
    self.videoFileURL = url;
    self.allComment =  [NSString stringWithFormat:@"大小 ：%@", [self getCommentSize:fileSize]];
    AVAsset *asset = [AVAsset assetWithURL:url];
    NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
    if([tracks count] > 0) {
        AVAssetTrack *videoTrack = [tracks objectAtIndex:0];
        //CGAffineTransform t = videoTrack.preferredTransform;//这里的矩阵有旋转角度，转换一下即可
        NSLog(@"=====hello  width:%ld===height:%ld",(long)videoTrack.naturalSize.width,(long)videoTrack.naturalSize.height);//宽高
        self.videoWidth = videoTrack.naturalSize.width;
        self.videoHeigh = videoTrack.naturalSize.height;
        
    }
    
    [self initPlayLayer];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
}
- (void)pressBackButton:(UIButton *)button
{
    
    
    
    NSString *fileName = @"videos";
    NSString *filePath = [self getDirectoryOfDocumentFileWithName:fileName];
    NSLog(@"===%@", filePath);
    if (filePath) {
        [self removeFileAtPath:filePath];
    }
    
    //首先判断是否是编辑页过来的
    _ComeFromEditVC = NO;
    UITabBarController *tabVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController *nav = [tabVc.viewControllers objectAtIndex:tabVc.viewControllers.count - 1];
    UIViewController *personVc;
    for (UIViewController *vc in nav.viewControllers) {
        if ([vc isKindOfClass:[XLVideoSetController class]]) {
            _ComeFromEditVC = YES;
            personVc = vc;
            break;
        }
    }
    
    if (_ComeFromEditVC) {
        
        if (personVc) {
            [nav popToViewController:personVc animated:NO];
        }else {
            [nav popToRootViewControllerAnimated:NO];
        }
        
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
    }else{
        if (self.weathNavbar == YES) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else {
            UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            UINavigationController *nav = [tabVC.viewControllers objectAtIndex:2];
            UIViewController *personVC;
            for (UIViewController *vc in nav.viewControllers) {
                if ([vc isKindOfClass:[XLPersonPageViewController class]]) {
                    personVC = vc;
                    break;
                }
            }
            if (personVC) {
                [nav popToViewController:personVC animated:NO];
            } else {
                [nav popToRootViewControllerAnimated:NO];
            }
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            
        }
    }
    
//        [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    
    
    
    
    //    if (self.presentingViewController) {
    //        [self dismissViewControllerAnimated:YES completion:nil];
    //    }
}
//获取文件路径
- (NSString *)getFilePath {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,  NSUserDomainMask , YES) firstObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"videoData"];
    return filePath;
}

- (NSString *)getQuPaiVideoPath {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    return [documentPath stringByAppendingPathComponent:@"com.duanqu.qupaisdk"];
}

- (NSString *)getDirectoryOfDocumentFileWithName:(NSString *)fileName {
    NSString *documentsPath = [self getDirectoryOfDocumentFolder];
    if (documentsPath) {
        return [documentsPath stringByAppendingPathComponent:fileName]; // 获取用于存取的目标文件的完整路径
    }
    
    return nil;
}

- (NSString *)getDirectoryOfDocumentFolder {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // 获取所有Document文件夹路径
    NSString *documentsPath = paths[0]; // 搜索目标文件所在Document文件夹的路径，通常为第一个
    
    if (!documentsPath) {
        NSLog(@"Documents目录不存在");
    }
    
    return documentsPath;
}
- (void)removeFileAtPath:(NSString *)filePath {
    NSError *error = nil;
    if ([self isFileExitsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        
        if (error) {
            NSLog(@"移除文件失败，错误信息：%@", error);
        }
        else {
            NSLog(@"成功移除文件");
        }
    }
    else {
        NSLog(@"文件不存在");
//        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (BOOL)isFileExitsAtPath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) {
        return YES;
    }
    
    return NO;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - PlayEndNotification
- (void)avPlayerItemDidPlayToEnd:(NSNotification *)notification
{
    if ((AVPlayerItem *)notification.object != _playerItem) {
        return;
    }
    [UIView animateWithDuration:0.3f animations:^{
        _playButton.alpha = 1.0f;
    }];
}

#pragma mark - 屏幕方向改变
- (BOOL)shouldAutorotate
{
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return  UIInterfaceOrientationPortrait;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIViewController *)getActivityViewController:(NSString *)controllerName {
    
    UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    while (topVC.presentedViewController) {
        
        topVC = topVC.presentedViewController;
        
        if ([[topVC.class description] isEqualToString:@"UINavigationController"]) {
            
            UINavigationController *navi = (UINavigationController *)topVC;
            
            if (navi && navi.viewControllers && navi.viewControllers.count > 0) {
                
                NSInteger count = navi.viewControllers.count;
                
                for (NSInteger i=count-1; i>=0; i--) {
                    
                    UIViewController *controller = [navi.viewControllers objectAtIndex:i];
                    
                    if ([[controller.class description] isEqualToString:controllerName]) {
                        
                        return controller;
                        
                    }
                    
                }
                
            }
            
        }
        
    }
    
    return nil;
    
}

@end
